package com.duo.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.duo.dto.*;
import com.duo.entity.*;
import com.duo.enums.errorcode.OrderBusinessCode;
import com.duo.exception.BaseException;
import com.duo.mapper.DishMapper;
import com.duo.mapper.OrderDetailMapper;
import com.duo.mapper.OrderMapper;
import com.duo.mapper.SetmealMapper;
import com.duo.result.PageResult;
import com.duo.service.OrderService;
import com.duo.service.ShoppingCartService;
import com.duo.service.TableService;
import com.duo.utils.OrderUtils;
import com.duo.utils.WeChatPayUtil;
import com.duo.vo.DishVO;
import com.duo.vo.OrderDetailVO;
import com.duo.vo.OrderSubmitVO;
import com.duo.vo.SetmealVO;
import com.duo.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: Xrx
 * @Description:
 * @CreateTime: 2023/7/8 19:25
 */
@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private TableService tableService;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private SetmealMapper setmealMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private WeChatPayUtil weChatPayUtil;

    @Autowired
    private WebSocketServer webSocketServer;


    /**
     * 用户下单
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO, User user) {
        // 1.校验购物车是否为空
        Long userId = user.getId();
        List<ShoppingCartCacheDTO> cart = shoppingCartService.showShoppingCart(userId);
        if (ObjectUtil.isEmpty(cart)) {
            log.error("购物车为空, userId: {}", userId);
            throw new BaseException(OrderBusinessCode.ORDER_CART_EMPTY_ERROR);
        }
        // 2.向订单表中插入数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setNumber(OrderUtils.generateOrderNumber());
        orders.setDeliverCode(OrderUtils.getDeliverCode());
        BigDecimal amount = BigDecimal.ZERO;
        for (ShoppingCartCacheDTO item : cart) {
            amount = amount.add(item.getAmount());
        }
        orders.setAmount(amount);
        orders.setUserId(userId);
        this.save(orders);
        orders = orderMapper.selectById(orders);
        // 3.向订单详情表中插入数据
        ArrayList<OrderDetail> orderDetails = new ArrayList<>();
        for (ShoppingCartCacheDTO item : cart) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(item, orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetails.add(orderDetail);
        }
        orderDetails.forEach(orderDetail -> {
            orderDetailMapper.insert(orderDetail);
        });
        // 4.删除购物车缓存
        shoppingCartService.cleanShoppingCart(userId);
        // 5.返回VO封装结果
        OrderSubmitVO orderSubmitVO = new OrderSubmitVO();
        BeanUtils.copyProperties(orders, orderSubmitVO);
        log.info("用户下单成功, orderSubmitVO: {}", orderSubmitVO);
        return orderSubmitVO;
    }

    /**
     * 订单支付
     * @param ordersPaymentDTO
     * @return
     */
    @Override
    public Orders payment(OrdersPaymentDTO ordersPaymentDTO, User user) {
        // 当前支付的用户信息
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Orders::getNumber, ordersPaymentDTO.getOrderNumber());
        Orders order = orderMapper.selectOne(wrapper);
        // 调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                order.getAmount(), //支付金额，单位 元
//                "多多点订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );
//
//        if (StrUtil.isNotBlank(jsonObject.getString("code"))
//                && jsonObject.getString("code").equals("ORDERPAID")) {
//            throw new BaseException(OrderBusinessCode.ORDER_PAID_ERROR);
//        }

//        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        return order;
    }

    /**
     * 历史订单查询
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery4User(OrdersPageQueryDTO ordersPageQueryDTO, User user) {
        Page<Orders> page = new Page<>(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Orders::getUserId, user.getId());
        wrapper.eq(StrUtil.isNotEmpty(ordersPageQueryDTO.getNumber()), Orders::getNumber, ordersPageQueryDTO.getNumber());
        // 订单状态 0待付款 1已付款 2已接单 3已完成 4已取消
        wrapper.eq(ObjectUtil.isNotEmpty(ordersPageQueryDTO.getStatus()), Orders::getStatus, ordersPageQueryDTO.getStatus());
        wrapper.orderByDesc(Orders::getOrderTime);
        Page<Orders> ordersPage = orderMapper.selectPage(page, wrapper);
        List<Orders> ordersList = ordersPage.getRecords();
        List<OrderSubmitVO> orderSubmitVOList = new ArrayList<>();
        ordersList.forEach(orders -> {
            OrderSubmitVO orderSubmitVO = new OrderSubmitVO();
            BeanUtils.copyProperties(orders, orderSubmitVO);
            orderSubmitVO.setTableName(tableService.getById(orders.getTableId()).getName());
            orderSubmitVOList.add(orderSubmitVO);
        });
        PageResult pageResult = new PageResult();
        pageResult.setTotal(ordersPage.getTotal());
        pageResult.setRecords(orderSubmitVOList);
        log.info("历史订单查询成功, pageResult: {}", pageResult);
        return pageResult;
    }

    /**
     * 查询订单详情
     * @param id
     * @return
     */
    @Override
    public OrderDetailVO details(Long id) {
        Orders orders = orderMapper.selectById(id);
        // 校验订单是否存在
        if (ObjectUtil.isNull(orders)) {
            log.error("查询订单详情失败, id: {}", id);
            throw new BaseException(OrderBusinessCode.ORDER_NOT_FOUND_ERROR);
        }
        OrderDetailVO orderDetailVO = new OrderDetailVO();
        BeanUtils.copyProperties(orders, orderDetailVO);
        orderDetailVO.setTableName(tableService.getById(orders.getTableId()).getName());
        LambdaQueryWrapper<OrderDetail> orderDetailWrapper = new LambdaQueryWrapper<>();
        orderDetailWrapper.eq(OrderDetail::getOrderId, id);
        List<OrderDetail> orderDetailList = orderDetailMapper.selectList(orderDetailWrapper);
        LambdaQueryWrapper<Dish> dishWrapper = null;
        LambdaQueryWrapper<Setmeal> setmealWrapper = null;
        for (OrderDetail orderDetail : orderDetailList) {
            Long dishId = orderDetail.getDishId();
            Long setmealId = orderDetail.getSetmealId();
            if (ObjectUtil.isNotNull(dishId)) {
                dishWrapper = new LambdaQueryWrapper<>();
                dishWrapper.eq(Dish::getId, dishId);
                Dish dish = dishMapper.selectOne(dishWrapper);
                DishVO dishVO = new DishVO();
                BeanUtils.copyProperties(dish, dishVO);
                dishVO.setDishId(dish.getId());
                orderDetailVO.getDishList().add(dishVO);
            } else {
                setmealWrapper = new LambdaQueryWrapper<>();
                setmealWrapper.eq(Setmeal::getId, setmealId);
                Setmeal setmeal = setmealMapper.selectOne(setmealWrapper);
                SetmealVO setmealVO = new SetmealVO();
                BeanUtils.copyProperties(setmeal, setmealVO);
                setmealVO.setSetmealId(setmeal.getId());
                orderDetailVO.getSetmealList().add(setmealVO);
            }
        }
        log.info("查询订单详情成功, OrderDetailVO: {}", orderDetailVO);
        return orderDetailVO;
    }

    /**
     * 用户取消订单
     * @param id
     */
    @Override
    public void userCancelById(Long id) throws Exception {
        Orders orders = orderMapper.selectById(id);
        // 校验订单是否存在
        if (ObjectUtil.isNull(orders)) {
            log.error("用户取消订单失败, id: {}", id);
            throw new BaseException(OrderBusinessCode.ORDER_NOT_FOUND_ERROR);
        }
        // 校验订单状态是否为待支付 (订单状态 订单状态 0待付款 1已付款 2已接单 3已完成 4已取消)
        if (orders.getStatus() >= 2) {
            // 若商家已接单，则无法取消订单
            throw new BaseException(OrderBusinessCode.ORDER_STATUS_ERROR);
        }
        if (orders.getStatus() == 1) {
            // 若用户只是处于已支付且商家未接单，则需要进行退款操作
            weChatPayUtil.refund(
                    orders.getNumber(), //商户订单号
                    orders.getNumber(), //商户退款单号
                    orders.getAmount(),   //退款金额，单位 元
                    orders.getAmount());  //原订单金额
            // 退款成功后，修改订单状态为已取消
            orders.setStatus(4);
        }
        orderMapper.updateById(orders);
        log.info("用户取消订单成功, id: {}", id);
    }

    /**
     * 用户催单
     * @param id
     */
    @Override
    public void reminder(Long id) {
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Orders::getId, id);
        Orders order = orderMapper.selectOne(wrapper);
        // 校验订单是否存在
        if (ObjectUtil.isNull(order)) {
            log.error("用户催单失败, id: {}", id);
            throw new BaseException(OrderBusinessCode.ORDER_NOT_FOUND_ERROR);
        }
        Map<Object, Object> map = new HashMap<>();
        map.put("type", 2); // 1-来单提醒 2-用户催单
        map.put("orderId", id);
        map.put("content", "订单号: " + order.getNumber() + " 的用户催单啦！");

        // 通过websocket向商家端推送消息
        webSocketServer.sendToAllClient(JSON.toJSONString(map));

    }

    /**
     * 商家接受订单
     * @param ordersConfirmDTO
     */
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders order = new Orders();
        // 订单状态 0待付款 1已付款 2已接单 3已完成 4已取消
        order.setStatus(2);
        order.setId(ordersConfirmDTO.getOrderId());
        orderMapper.updateById(order);
    }

    /**
     * 商家完成订单
     * @param id
     */
    @Override
    public void complete(Long id) {
        Orders order = new Orders();
        // 订单状态 0待付款 1已付款 2已接单 3已完成 4已取消
        order.setStatus(3);
        order.setId(id);
        orderMapper.updateById(order);
    }

    /**
     * 来单提醒
     * @param outTradeNo
     */
    @Override
    public void paySuccess(String outTradeNo, Long userId) {

        // 根据订单号查询当前用户的订单
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Orders::getNumber, outTradeNo);
        wrapper.eq(Orders::getUserId, userId);
        Orders order = orderMapper.selectOne(wrapper);
        // 订单状态 0待付款 1已付款 2已接单 3已完成 4已取消
        order.setStatus(1);
        orderMapper.updateById(order);

        // 通过websocket向客户端浏览器推送消息 type orderId content
        Map map = new HashMap();
        map.put("type", 1); // 1表示来单提醒 2表示客户催单
        map.put("orderId", order.getId());
        map.put("content", "订单号：" + outTradeNo);

        String json = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);
    }


}
